/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.factory.server.consumers;

import com.factory.server.bo.AbstractBusinessObject;
import java.util.LinkedList;
import org.springframework.context.ApplicationContext;

/**
 * Stores results from which consumer saves them to DB
 *
 * @author milos
 */
public class ResultQueue {

    private static LinkedList<AbstractBusinessObject> results;
    private boolean empty = true;
    private long timeQueued;
    private ApplicationContext applicationContext = null;

    public ResultQueue() {
        results = new LinkedList<AbstractBusinessObject>();
    }

    public synchronized void put(AbstractBusinessObject result) {
        results.add(result);
        empty = false;
        notifyAll();
//        ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) applicationContext.getBean("taskExecutor");
//        taskExecutor.notifyAll();


    }

    public synchronized AbstractBusinessObject get() {
        while (empty == true) {	//wait till something appears in the buffer
            try {
                wait();
            } catch (InterruptedException e) {
                //TODO
            }
        }
        if (results.isEmpty()) {
            empty = true;
            return null;
        }
        return results.pop();
    }

    public synchronized boolean isEmpty() {
        return empty;
    }

    public long getTimeQueued() {
        return this.timeQueued;
    }

    public synchronized void setResults(LinkedList<AbstractBusinessObject> results) {
        this.results = results;
    }

    public LinkedList<AbstractBusinessObject> getResults() {
        return this.results;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}
